package com.ihai.spring.boot.sample.distributed.counter.remote;

import com.ihai.spring.boot.sample.distributed.counter.manager.CounterManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * DESC
 *
 * @author 张驰
 * @date 2019/12/24
 */
public class NodeManager implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(NodeManager.class);

    private static List<Node> clusters = new ArrayList<>();
    private static boolean isMaster;
    private static Node master;
    private static Node current;

    public static void addCluster(Node node){
        if(!clusters.contains(node)){
            NodeManager.clusters.add(node);
        }
    }
    public static List<Node> getClusters(){
        return clusters;
    }
    public static void setClusters(List<Node> clusters){
        NodeManager.clusters.clear();
        for(Node node : clusters){
            NodeManager.clusters.add(node);
        }
    }
    public static void setCurrent(Node node){
        current = node;
    }
    public static void removeCluster(Node node) {
        clusters.remove(node);
    }

    public static void resetMaster(){
        Node tmp = MasterSelector.selectMaster(clusters);
        if(tmp != null && !tmp.equals(master)) {
            master = tmp;
            if(master.equals(current)){
                isMaster = true;
            }else{
                isMaster = false;
            }
            CounterManager.getInstance().isMaster(isMaster);
        }
    }

    public static Node getMaster(){
        return master;
    }

    public static boolean isMaster(){
        return isMaster;
    }

    public static Node getCurrent() {
        return current;
    }

}
